Imports System.IO
Public Class TreeForm

    Public FormParent As MainForm

    Dim rootNode As TreeNode
    Public RootFolder As String

    Private Sub tsRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsRefresh.Click
        SearchNow
    End Sub

    Private Sub TreeForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SearchNow()
    End Sub
    Private Sub SearchNow()

        'Searching
        tv.Nodes.Clear()
        doSearch = AddressOf SearchFolder
        rootNode = tv.Nodes.Add(RootFolder)
        
        If Not SearchFolderWorker.IsBusy Then
            SearchFolderWorker.RunWorkerAsync()
        End If
    End Sub

    Dim ar As Object
    Private Sub SearchFolderWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles SearchFolderWorker.DoWork

        ar = Me.BeginInvoke(doSearch, New Object() {rootNode, RootFolder})
    End Sub

    Delegate Sub SearchFolderDelegate(ByVal node As TreeNode, ByVal path As String)
    Dim doSearch As SearchFolderDelegate

    Sub SearchFolder(ByVal node As TreeNode, ByVal path As String)
        Dim Folders As String() = Directory.GetDirectories(path)
        For Each Folder As String In Folders
            Dim FolderName As String = IO.Path.GetFileNameWithoutExtension(Folder)
            Dim n As TreeNode = node.Nodes.Add(FolderName)
            n.Tag = Folder
            n.ImageIndex = 0
            n.SelectedImageIndex = 1
            Me.Text = Folder
            'Search Sub Folder
            SearchFolder(n, Folder)
        Next
    End Sub


    Private Sub tv_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tv.AfterSelect
        Me.Text = e.Node.Tag
    End Sub

    Private Sub tsGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsGo.Click
        If tv.SelectedNode.Tag IsNot Nothing Then
            With FormParent
                .LoadFolderAndFiles(tv.SelectedNode.Tag, .ActiveView)
            End With
        End If
    End Sub
End Class